import React, { useState } from 'react';
import { saveAs } from 'file-saver';
import Modal from '../components/Modal';

interface SidebarProps {
  activeNote: Note | null;
  notes: Note[];
  onNoteSelect: (noteId: number) => void;
  onNoteAdd: () => void;
  onNoteDelete: (noteId: number) => void;
}

const Sidebar: React.FC<SidebarProps> = ({activeNote, notes, onNoteSelect, onNoteAdd, onNoteDelete }) => {
  const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
  const [noteToDelete, setNoteToDelete] = useState<number | null>(null);

  const handleExportNotes = () => {
    const notesData = localStorage.getItem('notesapp-notes');
    if (!notesData) return;

    const notes = JSON.parse(notesData);
    const csvContent = [
      ["ID", "Title", "Body", "Updated"].join(","),
      ...notes.map((note: Note) => [
        note.id,
        note.title,
        note.body,
        new Date(note.updated).toLocaleString()
      ].join(","))
    ].join("\n");

    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
    saveAs(blob, 'notes.csv');
  };

  const handleImportNotes = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (!file) return;

    const reader = new FileReader();
    reader.onload = (e) => {
      const text = e.target?.result as string;
      const lines = text.split('\n').slice(1);
      const newNotes = lines.map(line => {
        const [id, title, body, updated] = line.split(',');
        return { id: Number(id), title, body, updated };
      });

      localStorage.setItem('notesapp-notes', JSON.stringify(newNotes));
      window.location.reload(); 
    };
    reader.readAsText(file);
  };

  const openDeleteModal = (noteId: number) => {
    setNoteToDelete(noteId);
    setIsDeleteModalOpen(true);
  };

  const closeDeleteModal = () => {
    setIsDeleteModalOpen(false);
    setNoteToDelete(null);
  };

  const confirmDelete = () => {
    if (noteToDelete !== null) {
      onNoteDelete(noteToDelete);
    }
    closeDeleteModal();
  };

  return (
    <div className="notes__sidebar">
      <button className="notes__add" type="button" onClick={onNoteAdd}>
        添加新的笔记 📒
      </button>
      <div className="operation__container" >
        <button className="notes__export" type="button" onClick={handleExportNotes}>
          Export Notes
        </button>
        <input
          type="file"
          accept=".csv"
          title="import-notes"
          id="import-notes"
          onChange={handleImportNotes}
        />
        <button
          className="notes__import"
          type="button"
          onClick={() => document.getElementById('import-notes')?.click()}
        >
          Import Notes
        </button>
      </div>
      <div className="notes__list">
        {notes.map((note) => (
          <div 
            key={note.id} 
            className={`
              notes__list-item 
              ${activeNote && activeNote.id === note.id ? 'notes__list-item--selected' : ''}`
            }
            onClick={() => onNoteSelect(note.id)}
          >
            <div className="notes__small-title">{note.title}</div>
            <div className="notes__small-body">{note.body.substring(0, 60)}{note.body.length > 60 ? "..." : ""}</div>
            <div className="notes__small-updated">
              {new Date(note.updated).toLocaleString()}
            </div>
            <div 
              className="notes__delete-button" 
              onClick={(e) => {
                e.stopPropagation();
                openDeleteModal(note.id);
              }}
            >
              X
            </div>
          </div>
        ))}
      </div>
      <Modal 
        isOpen={isDeleteModalOpen}
        onRequestClose={closeDeleteModal}
        onConfirm={confirmDelete}
        content="确认要删除该笔记吗？"
      />
    </div>
  );
};

export default Sidebar;

interface Note {
  id: number;
  title: string;
  body: string;
  updated: string;
}
